package com.xk.meeting.utils;

import java.security.MessageDigest;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {
	private static final String KEY = "cookie@ybzy.com123!";

	/**
	 * 指令浏览器创建cookie文件用的方法
	 * 
	 * @param username:放到cookie信息里用户名
	 * @param req
	 * @param resp:调用addCookie方法得response对象
	 * @param sec:设置Cookie失效日期,单位秒
	 */
	public static void createCookies(String username, HttpServletRequest req, HttpServletResponse resp, int sec) {
		Cookie userCookie = new Cookie("userKey", username);
		Cookie ssidCookie = new Cookie("ssid", md5Encrypt(username));
		userCookie.setMaxAge(sec);
		ssidCookie.setMaxAge(sec);
		resp.addCookie(userCookie);
		resp.addCookie(ssidCookie);
	}

	/**
	 * 这个方法得作用就是加密,把一个明文加载成密文
	 * 
	 * @param ss
	 * @return
	 */
	public static String md5Encrypt(String ss) {
		ss = ss == null ? "" : ss + KEY;
		char[] md5Digist = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
		byte[] ssarr = ss.getBytes();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");//md5  sha1  sha2  加密算法
			md.update(ssarr);//把明文放到MessageDigest的对象实例去,更新数据
			byte[] mssarr = md.digest();
			
			int len = mssarr.length;
			char[] str = new char[len*2];
			int k = 0;//计数
			
			for(int i=0;i<len;i++) {
				byte b = mssarr[i];
				str[k++] = md5Digist[b >>> 4 & 0xf];
				str[k++] = md5Digist[b & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
